<template>
  <div id="cpp">
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <!-- <el-form-item label="">
            <el-input v-model="formInline.query"></el-input>
          </el-form-item>-->
      <el-form-item label="团队">
        <el-select-v2 allow-create v-model="teamid" clearable @change="teamchange" :options="teams1"
          filterable></el-select-v2>
      </el-form-item>
      <el-form-item label="学员">
        <el-select-v2 v-model="usersd" multiple :options="us1" clearable collapse-tags filterable
          :style="{ width: '200px' }" allow-create></el-select-v2>
      </el-form-item>
      <el-form-item label="时间">
        <el-date-picker v-model="time" type="daterange" range-separator="-" start-placeholder="开始日期"
          end-placeholder="结束日期" :shortcuts="shortcuts"></el-date-picker>
      </el-form-item>
      <el-form-item label="类型">
        <el-select v-model="typen" style="width: 200px" placeholder="请选择">
          <el-option label="全部" value="all"></el-option>
          <el-option label="提交评测" value="scoket"></el-option>
          <el-option label="观看视频" value="video"></el-option>
          <!-- <el-option label="浏览页面" value="router"> </el-option> -->
          <el-option label="查看题单" value="查看题单"></el-option>
          <el-option label="查看题目" value="查看题目"></el-option>
          <el-option label="报名比赛" value="报名比赛"></el-option>
          <el-option label="完成比赛" value="完成比赛"></el-option>
          <el-option label="知码狐账号登录" value="知码狐账号登录"></el-option>
        </el-select>
      </el-form-item>
      <br />
      <!-- <el-form-item label="参数">
          <el-input v-model="formInline.query"></el-input>
          </el-form-item>-->
      <!-- <el-form-item label="查询方式">
          <el-radio-group v-model="radio">
            <el-radio :label="1">手机查询</el-radio>
            <el-radio :label="2">ID查询</el-radio>
            <el-radio :label="3">用户名查询</el-radio>
          </el-radio-group>
          </el-form-item>-->
      <el-row>
        <el-col :span="12">
          <el-form-item label="总条数:">{{ count }} &nbsp;&nbsp;&nbsp;</el-form-item>
          <el-form-item label="用户数:">{{ usercount }}</el-form-item>
        </el-col>
        <el-col :span="12" class="text-right">
          <el-button type="primary" @click="start(radio)">查询</el-button>
          <el-button type="primary" @click="() => download()">下载当前页</el-button>
          <el-button type="primary" @click="() => download(true)">下载全部</el-button>
        </el-col>
      </el-row>
    </el-form>
    <!-- <el-tabs v-model="activeName">
      <el-tab-pane label="index" name="index">-->
    <el-table :data="mytableDate" style="width: 100%" :row-class-name="tableRowClassName" height="77vh">
      <el-table-column prop="_userid_" label="用户id" width="180"></el-table-column>
      <el-table-column prop="_username_" label="学员名" width="180"></el-table-column>
      <el-table-column prop="type" label="类型"></el-table-column>
      <el-table-column prop="info" label="参数"></el-table-column>
      <el-table-column prop="time" label="时间"></el-table-column>
      <el-table-column prop="attr" label="其他信息"></el-table-column>
    </el-table>
    <!-- </el-tab-pane>
        <el-tab-pane label="index2" name="index2">
          <Ech></Ech>
        </el-tab-pane>
      </el-tabs>-->
    <el-pagination class="pager" @size-change="handleSizeChange" @current-change="(e) => handleCurrentChange(e)"
      :page-sizes="[10, 20, 50, 100, 200, 500]" :page-size="formInline.line" :current-page="currentPage2"
      layout="total, sizes, prev, pager, next, jumper" :total="count"></el-pagination>
  </div>
</template>

<script setup lang="ts">
import { AxiosPromise } from "axios";
import { ElMessage } from "element-plus";
import moment from "moment";
import { invert } from "underscore";
import {
  computed,
  onMounted,
  reactive,
  ref,
  watch
} from "vue";
import {
  asyncselectteams,
  asyncselectteamselectuser,
  asyncselectteamuser,
  online,
  selecteamtteams,
} from "../api/index";
import Studycodemodel from "../mysql_interface/studycodemodel";
import FetchApi, { logdata } from "./api";
import { getExceltodownload } from "./excel";
import { OJMethod } from "./type";
type IIlogs = {
  _userid_?: number | string;
  _username_?: string;
  __to__?: string;
  __from__?: string;
  ismatch?: boolean;
  questionname?: string;
  questionid?: string;
  type: string;
  _method_?: string;
  body?: string;
  time?: string;
  status?: string;
  "__tag__:__receive_time__": string | number | Date;
  coursename?: string;
  watchtime?: string;
  typename1?: string;
};

type IIlogsee = {
  _userid_?: number | string;
  _username_?: string;
  type?: string;
  info?: string;
  time?: string;
  attr?: string;
};
const time = computed<[Date, Date]>({
  get() {
    return [formInline.from, formInline.to];
  },
  set(v: [Date, Date]) {
    formInline.from = v[0];
    formInline.to = v[1];
  },
});
const isAdmin = computed(() => {
  if (!user.ID) return false;
  const team = teams.value.find((e) => e.ID === teamid.value);
  if (team?.userid === user.ID) return 1;
  const a = team?.teamuser?.find((v) => v.userid === user.ID);
  if (a) {
    return a.isAdmin;
  }
  if (user.remarks === "销售助教") return 2;
  return false;
});
const tableData = ref<IIlogs[]>([]);
const currentPage2 = ref(1);
const logstoreName = ref("ojhte");
const _OJMethod = invert(OJMethod);
const user = reactive<Studycodemodel.Iuser>({});
const activeName = ref("index");
const teams1 = computed(() => {
  const n = teams.value.map((e) => {
    return {
      value: e.ID,
      label: e.name,
    };
  });

  return [{
    value: 0,
    label: '全部',
  }].concat(...n)
});

const us1 = computed(() => {
  return us.value.map((e) => {
    return {
      value: e.userid,
      label: e.user?.name,
    };
  });
});

const radio = ref(1);
const _tmp: any[] = [
  "学员名id",
  "学员名称",
  "类型",
  "参数",
  "时间",
  "详细内容",
];
// const query = " not type:fetch ";

const mytableDate = computed<IIlogsee[]>(() => {
  console.log(tableData.value)
  return tableData.value.map(_tableDatamap);
});

function _tableDatamap(v: IIlogs): IIlogsee {
  const { _userid_, _username_, type, _method_, body, typename1, ...data } =
    v;
  if (type === "fetch") {
    return {
      _userid_,
      _username_,
      // type: "请求内容",
      type: _method_
        ? _OJMethod[_method_]
          ? _OJMethod[_method_]
          : "请求内容"
        : "请求内容",
      info: typename1,
      time: momentMM(v),
      // attr: body,
    };
  } else if (type === "scoket") {
    const { questionname } = data;
    return {
      _userid_,
      _username_,
      type: "提交评测",
      info: questionname,
      time: momentMM(v),
      // attr: JSON.stringify(data),
    };
  } else if (type === "router") {
    const { __to__ } = data;
    return {
      _userid_,
      _username_,
      type: "浏览页面",

      info: __to__,
      time: momentMM(v),
      // attr: JSON.stringify(data),
    };
  } else if (type === "video") {
    const { coursename, watchtime } = data;
    return {
      _userid_,
      _username_,
      type: "观看视频",
      info: coursename,
      time: momentMM(v),
      // watchtime,
      attr: watchtime,
    };
  }
  return {
    _userid_,
    _username_,
    type: "其他内容",
    info: "",
    time: momentMM(v),
    // attr: JSON.stringify(data),
  };
}
function onchange2(value: string) { }
const teamid = ref();
const checked = ref(false);
const formInline = reactive<logdata>({
  query: "* | with_pack_meta",
  line: 20,
  offset: 0,
  projectName: "htetest1",
  logstoreName: "ojhte",
  from: new Date(moment().subtract(7, "days").unix() * 1000),
  to: new Date(moment().add(1, "days").unix() * 1000),
  reverse: true,
});
function momentMM(t: IIlogs) {
  return moment(Number(t["__time__"]) * 1000).format(
    "YYYY-MM-DD HH:mm:ss"
  );
}
async function download(t?: boolean) {
  if (!t) {
    const arr = [_tmp].concat(
      mytableDate.value.map((e) => Object.values(e))
    );
    getExceltodownload(arr, "学员日志");
  } else {
    const { line, offset, ...f } = formInline;
    let data: IIlogs[] = [];
    const n: (() => AxiosPromise<IIlogs[]>)[] = [];
    for (let l = 0; l < count.value; l = l + 99)
      n.push(() => {
        return FetchApi({
          ...f,
          line: 99,
          offset: l,
        });
      });
    Promise.all(n.map((e) => e()))
      .then((e) => {
        const arr = e
          .map((n) => n.data)
          .flat()
          .map(_tableDatamap)
          .map((e) => Object.values(e));

        const team = teams.value.find((f) => f.ID == teamid.value);
        const name = `${team?.name ? team.name : "学生日志"}_${moment(
          formInline.from
        ).format("YYYYMMDD")}-${moment(formInline.to).format("YYYYMMDD")}`;
        getExceltodownload(arr, name);
      })
      .catch((f) => {
        ElMessage.error(f);
      });
  }
}
const users = ref<Array<string | number | undefined>>([]);
const username = ref<Array<string | number | undefined>>([]);
const count = ref(0);
const usercount = ref(0);
function tableRowClassName({ row, rowIndex }: any) {
  if (rowIndex % 2 === 1) {
    return "warning-row";
  } else {
    return "success-row";
  }
}
const usersd = ref<number[]>([]);
watch(
  () => usersd.value,
  () => {
    if (usersd.value.length > 21) {
      usersd.value = usersd.value.filter((e, k) => k < 20);
      ElMessage.error("用户最多可以选择20人");
    }
  }
);
const index = ref(0);
// 团队用户
const us = ref<Studycodemodel.Iteamuser[]>([]);
// 查询类型
const typen = ref<"all" | "scoket" | "router" | "video" | "题单" | "题目">(
  "all"
);
// 用户手机号

async function start(i: number) {
  index.value = 0;
  let _us = us.value;

  const d = new URLSearchParams(location.search.substring(1));
  const n = d.get("user");
  const m = d.get("username");
  const team = teams.value.find((e) => e.ID === teamid.value);
  if (teamid.value) {
    radio.value = 1;
    if (user.type === "admin") {
      const { rows } = await asyncselectteamuser({
        teamid: teamid.value,
        phonenum: true,
      });
      us.value = rows;
    } else {
      us.value = await asyncselectteamselectuser({
        teamid: teamid.value,
        phonenum: true,
      });
      us.value.push({ userid: team?.userid, user: team?.user });
    }
  } else if (m) {
    const _n = m.split(",");
    username.value = _n.slice(0, 20);
    radio.value = 3;
  } else if (n) {
    users.value = [];
    radio.value = 2;
  }
  if (i) {
    radio.value = i;
  }
  await onSubmit();
}
async function onSubmit() {
  if (!user?.ID) {
    ElMessage.info("请登录");
    return;
  }
  if (!isAdmin.value) {
    ElMessage.error("权限不足");
    return;
  }
  let str = "";
  let where = "where 1 = 1"
  if (radio.value === 1) {
    if (teamid.value) {
      str = `* and _teamids_:${teamid.value}  `;
    }
    if (usersd.value.length) {
      where = where + ` and _userid_ in (${usersd.value.join(',')})`
    }
  }
  if (["scoket", "router", "video"].includes(typen.value)) {
    formInline.query = `* and type:${typen.value}   ${str ? '(AND ' + str + ')' : ''}`;
  } else if (typen.value === "all") {
    formInline.query = str;
  } else {
    formInline.query = `* and _method_:${OJMethod[typen.value]}    ${str ? '(AND ' + str + ')' : ''} `;
  }

  const { data } = await FetchApi(
    Object.assign({}, formInline, {
      offset: Number(formInline.offset),
      query: formInline.query + " | select * " + where + ` order by __time__ desc ` + ` limit ${formInline.offset},${formInline.line}`,
    })
  );
  tableData.value = data;
  await getcount(formInline.query, where);
}
async function getcount(str: string, where: string) {
  const { data } = await FetchApi(
    Object.assign({}, formInline, {
      query: str + "| SELECT count(*) as count , count(DISTINCT(_userid_)) as usercount " + where,
      offset: 0,
    })
  );
  count.value = Number(data[0].count);
  usercount.value = Number(data[0].usercount)
}
function handleSizeChange(d: number) {
  formInline.line = d;
  onSubmit();
}
function handleCurrentChange(v: number) {
  console.log(v);

  formInline.offset = (formInline.line ? formInline.line : 0) * (v - 1);
  currentPage2.value = v;
  let n = 0;
  index.value = 0;
  onSubmit();
}

const teams = ref<Studycodemodel.Iteam[]>([]);

function teamchange(v: string) {
  location.href = "/logs.html?teamid=" + v;
}
onMounted(async () => {
  const d = new URLSearchParams(location.search.substring(1));
  try {
    const e = await online();
    Object.assign(user, e);
  } catch (e) {
    location.href = "/";
  }

  teamid.value = Number(d.get("teamid")) ? Number(d.get("teamid")) : 0;
  const t = await selecteamtteams({ phonenum: true });
  teams.value = t.rows;
  if (user?.remarks === "销售助教") {
    asyncselectteams({ phonenum: true, grade: 0 }).then((d) => {
      for (const f of d.rows) {
        if (!teams.value.find((e) => e.ID === f.ID)) {
          teams.value.push(f);
        }
      }
    });
  }

  await start(0);
});

const shortcuts = [
  {
    text: "上周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: "本周",
    value: () => {
      const end = new Date();

      const start = moment().day(1).unix() * 1000;
      return [start, end];
    },
  },
  {
    text: "本月",
    value: () => {
      const end = new Date();
      const start = moment().date(1).unix() * 1000;
      return [start, end];
    },
  },
  {
    text: "最近90天",
    value: () => {
      const end = new Date();
      const start = moment().date(-90).unix() * 1000;
      return [start, end];
    },
  },
]

</script>

<style>
#app {
  /* height: 100vh; */
}

#app .el-form-item {
  margin-bottom: 12px;
}

.el-table .warning-row {
  --el-table-tr-background-color: #fff;
}

.el-table .success-row {
  --el-table-tr-background-color: #f5f5f5;
}

#cpp {
  background-color: #fff;
  padding: 20px;
  height: 100%;
}

.pager {
  margin: 15px 0;
  display: flex;
  justify-content: flex-end;
}
</style>
